package com.cy.lib.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by CY on 2015/8/12.
 */
public class PackageUtils {

    /**
     * 收集设备数据
     */
    public static Map<String, String> getDeviceInfo(Context context) {

        Map<String, String> mInfoMap = new HashMap<String, String>();
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            if (info != null) {
                mInfoMap.put("versionName", info.versionName);
                mInfoMap.put("versionCode", info.versionCode + "");
            }
            // android.os.Build.MODEL设备名
            mInfoMap.put("model", android.os.Build.MODEL);
            // 获取系统版本
            mInfoMap.put("SDK", +android.os.Build.VERSION.SDK_INT + "");
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            // IMEI 设备唯一标识
            String imei = tm.getDeviceId();
            // 电话号码
            String tel = tm.getLine1Number();
            // 设备软件版本
            // String deviceSoftversion = tm.getDeviceSoftwareVersion();
            mInfoMap.put("imei", imei);
            mInfoMap.put("tel", tel);
            // mInfoMap.put("imei", deviceSoftversion);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mInfoMap;
    }

    /**
     * 获取设备信息
     *
     * @param context
     * @return
     */
    public static String getDeviceInfoStr(Context context) {
        Map<String, String> map = getDeviceInfo(context);
        Set<String> set = map.keySet();
        StringBuffer sb = new StringBuffer();
        for (String key : set) {
            sb.append(key + "=").append(map.get(key) + ";");
        }
        Log.d("deviceinfo", sb.toString() + "");
        return sb.toString();
    }


    /**
     * 获取应用版本名称
     *
     * @return
     * @throws Exception
     */
    public static String getVersionName(Context context) throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(
                context.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }
}
